import React from "react";
import { BrowserRouter, Routes, Route, Navigate } from "react-router-dom";
import { useAppSelector } from "../store/hooks";
import { RouteRowState } from "../types";
import { ROUTER_LIST } from "./routes";

interface PropsType extends RouteRowState {}

const BeforeEachRouter: React.FC<PropsType> = (props) => {
  const token = useAppSelector((state) => state.user.token);
  if (props.authLogin && !token) return <Navigate to="/login"></Navigate>;
  else return props.element;
};

const renderView = (routes: RouteRowState[]) => {
  return routes.map((v, i) => {
    return (
      <Route
        path={v.path}
        element={<BeforeEachRouter {...v}></BeforeEachRouter>}
        key={i}
      >
        {/* 递归渲染 */}
        {v.children && renderView(v.children)}
      </Route>
    );
  });
};

const Index: React.FC = () => {
  const RouterView = renderView(ROUTER_LIST);

  return (
    <BrowserRouter>
      <React.Suspense>
        <Routes>{RouterView}</Routes>
      </React.Suspense>
    </BrowserRouter>
  );
};

export default Index;
